package main;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

import missObjects.AirplaneUse;
import RofMission.RofMission;
import RofMission.RofMissionParams;
import db.RofDB;

public class Mission {
	
	private static Logger LOGGER = Logger.getLogger("RofLogger");
	
	/**
	 * Initialization of access and value before windows opening
	 * @throws Exception
	 */
	public static void init(RofMissionParams params) throws Exception {
		LOGGER.info("Lancement de l'application");

		// map properties loading
		MapProp.load();
		List <MapFile> test = MapProp.getMapFiles("standard");
		
		// planes properties loading
		PlanesProp.load();
		
		// General Properties loading
		Prop.load();

		// params initialization
		params.initFromProps();
		
		// DB access and init.
		try {
			RofDB.open();
			RofDB.init();
		} catch (Exception e) {
			LOGGER.severe("Database access Error");
			throw(e);
		}
	} 
	
	/**
	 * Closing of application
	 * @throws Exception
	 */
	public static void close(RofMissionParams params) throws Exception {
		
		params.saveToProps();
		
		// Properties Saving
		Prop.save();
		
		// DB access 
		RofDB.close();
		
		// End Message
		LOGGER.info("Lancement de l'application");
		
		//LOGGER Handlers closing
		Handler[] LoggerHandlers = null;
		LoggerHandlers=LOGGER.getHandlers();
		for (Handler fh : LoggerHandlers) {
			if (fh != null) fh.close();
		}
	} 
	
	public static void generate(RofMissionParams params) throws Exception  {
		Double Xmax=params.getXmax()+params.getXmargin();
		Double Xmin=Math.max(params.getXmin()-params.getXmargin(),0);
		Double Zmax=params.getZmax()+params.getZmargin();
		Double Zmin=Math.max(params.getZmin()-params.getZmargin(),0);
		
		String request="select indexInFile, fileID from Airfield where ("+
				"Xpos <= "+Xmax+" AND Xpos  >= "+Xmin+" AND "+
				"Zpos <= "+Zmax+" AND Zpos  >= "+Zmin+
				")";
		RofDB.cleanAirfieldSelected();
		RofDB.addAirfieldSelected(request);

		Path path=Paths.get(params.getMissionName());
		String tmpPath=path.getParent().toString()+"\\";
		String tmpName=path.getFileName().toString();
		String name=tmpName.replace(".Mission", "");
		
		List <Integer> fileIDList=MapProp.getMapfileID(params.getCurrentMap(), params.getFlagAirfieldOnly());
		RofMission.generate(tmpPath, name, fileIDList, params);
		LOGGER.info("End of text files generation");
		//BUG
		//int status=ExecuteResaver(params);
		
	}
	
	/**
	 * Use plane model string to update script and models in RofMissionParams
	 * @param use : LAND or TAKEOFF
	 * @param planeModel : name of the model
	 * @param params : object containing settings
	 */
	public static void  UpdatePlaneInfo(AirplaneUse use, String planeModel, RofMissionParams params) {
		String model=PlanesProp.getModel(planeModel);
		String script=PlanesProp.getScript(planeModel);
		
		params.setPlaneScript(use,script);
		params.setPlaneModel(use, model);
		
	}
	
	/**
	 * execute Ro mission resaver using MSDOS command
	 * @param params parameters of mission (including RofPAth and mission file)
	 * @throws IOException 
	 * @throws InterruptedException 
	 */
	private static int  ExecuteResaver(RofMissionParams params) throws IOException, InterruptedException {

        String MSDOSCommand=Prop.get("missionResaverScript");

        String missResaverPath=params.getRofPath()+"\\bin_editor\\mission_resaver";
        String RofDataPath=params.getRofPath()+"\\data";
        String MissionName=params.getMissionName();
        
		Runtime rt = Runtime.getRuntime();
        
        Process pr = rt.exec("cmd /c "+MSDOSCommand+" \""+missResaverPath+"\" \""+RofDataPath+"\" \""+MissionName+"\"");

        //DEBUG
        BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));

        String line=null;

        while((line=input.readLine()) != null) {
        	LOGGER.fine(line);
        }

        int exitVal = pr.waitFor();
        return(exitVal);

	}
}
